//
//  RHGroupAddUserVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2024/11/14.
//

#import "RHGroupAddUserVC.h"
#import <MGSwipeButton.h>
#import "RHGroupAddUserCell.h"
#import "RHUserModel.h"
#import "RHUserDetailVC.h"
#import "RHAddUserVC.h"
#import "RHSearchView.h"
#import "RHUserGroupModel.h"

@interface RHGroupAddUserVC ()<UITableViewDelegate,UITableViewDataSource,QMUITextFieldDelegate>
@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *userArr;

//由于上拉加载及分类不方便在下级实现,所以抽到上层处理
@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic, strong) RHSearchView *searchView;

@property (nonatomic, strong) NSMutableArray *selectArr;

@property (nonatomic, strong) QMUIButton *sureBtn;
@end

@implementation RHGroupAddUserVC

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"添加用户".rh_localized;
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    self.numOfPage = 10;
    [self getUserList];
    [self setupUI];
    self.selectArr = [NSMutableArray array];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
}

-(void)getUserList
{
    [self.selectArr removeAllObjects];
    [self updateBtn];
    [QMUITips showLoadingInView:self.view];
    NSDictionary *para = @{@"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"email":ValidNullData(self.searchView.searchTextField.text)
                           
    };
    [RHUserModel startGetWithCompletionAPIKey:H_getUserList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            NSInteger total = [request.responseObject[@"total"] integerValue];
            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
        
            //下拉刷新
            if(self.requestType == RequestTypeRefresh){
                self.userArr = [resultModel.data mutableCopy];
                [self.tableView endHeaderRefresh];
            }else{//上拉加载
                [self.tableView endFooterRefresh];
                [self.userArr addObjectsFromArray:resultModel.data];
                
            }
            if(self.currentPage >= self.totalPage){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
            [self.tableView reloadData];
            [self updateBtn];
        }
    
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        [self.tableView endFooterRefresh];
    }];
    
}

#pragma mark 分组添加用户
-(void)groupAddUser
{
    kWeakSelf;
    if (self.selectArr.count == 0) {
        return;
    }
    [QMUITips showLoading:@"" inView:self.view];
    NSDictionary *para = @{
                            @"id":@(self.groupModel.groupId),
                            @"userIdList":self.selectArr
                          };
    [QMUITips showLoadingInView:kAppWindow];
    [BaseModel startWithCompletionAPIKey:H_groupAddUser argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        if(resultModel.code == 200){
            [QMUITips showSucceed:@"成功".rh_localized inView:self.view hideAfterDelay:1];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter]postNotificationName:UserGroupListNeedUpdateNotification object:nil];
                if (weakSelf.addFinishBlock) {
                    weakSelf.addFinishBlock();
                }
                [weakSelf.navigationController popViewControllerAnimated:YES];
            });
            
        }
        } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
            
        }];

}


- (void)setupUI{
    kWeakSelf;
    _searchView = [[RHSearchView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 55)];
    [self.view addSubview:_searchView];
    _searchView.delegate = self;
    _searchView.searchTextField.placeholder = @"请输入用户邮箱".rh_localized;
    
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    [_tableView setBackgroundColor:CFTabViewBgColor];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHGroupAddUserCell class] forCellReuseIdentifier:@"RHGroupAddUserCell"];
    [self.view addSubview:_tableView];
    _tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"没有数据".rh_localized detailStr:@""];
    
    if (@available(iOS 11.0, *)) {
        _tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        //_resultTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    if (@available(iOS 15.0, *)) {
        _tableView.sectionHeaderTopPadding = 0;
        //_resultTableView.sectionHeaderTopPadding = 0;
    }
    
    
   
    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView endFooterResetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        [weakSelf getUserList];
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getUserList];
    }];
    
    QMUIButton *sureBtn = [[QMUIButton alloc]init];
    [sureBtn setTitle:@"确定".rh_localized forState:UIControlStateNormal];
    [sureBtn setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
    [sureBtn setCornerRadius:8];
    [sureBtn setBackgroundColor:CMainColorGreen];
    [sureBtn addTarget:self action:@selector(groupAddUser) forControlEvents:UIControlEventTouchUpInside];
    sureBtn.enabled = NO;
    [self.view addSubview:sureBtn];
    self.sureBtn = sureBtn;
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
        make.height.offset(50);
    }];
    
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.equalTo(sureBtn.mas_top).offset(-15);
        make.top.equalTo(weakSelf.searchView.mas_bottom);
    }];
    
    self.tableView.ly_emptyView = [LYEmptyView emptyViewWithImageStr:@"nodata_icon_1" titleStr:@"No data" detailStr:@""];
    
    
}



#pragma mark -------  tableView delegate -------

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewAutomaticDimension;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.userArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.0;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.1;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    RHUserModel *userModel = self.userArr[indexPath.row];
    RHGroupAddUserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RHGroupAddUserCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    cell.usermodel = userModel;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    RHUserModel *user = [self.userArr safeObjectAtIndex:indexPath.row];
    user.isSelected = !user.isSelected;
    if (user.isSelected) {
        if (![self.selectArr containsObject:@(user.userId)]) {
            [self.selectArr addObject:@(user.userId)];
        }
    }else{
        [self.selectArr removeObject:@(user.userId)];
    }
    [self updateBtn];
    [tableView reloadData];
}
-(void)updateBtn
{
    self.sureBtn.enabled = self.selectArr.count>0;
    [self.sureBtn setTitle:[NSString stringWithFormat:@"%@ (%ld/%ld)",@"确定".rh_localized,self.selectArr.count,self.userArr.count] forState:UIControlStateNormal];
}

#pragma mark ------- textField delegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    [self getUserList];
    [self.searchView resignFirstResponder];
    
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    [self.tableView.mj_footer resetNoMoreData];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
 
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.05 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self getUserList];
        [self.searchView resignFirstResponder];
    });
    return YES;
}

#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}


-(void)dealloc
{
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}



@end
